﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace PO_2011.Filter
{
    class NormalMap : BitmapFastPixel
    {
        public static Bitmap create(Bitmap image)
        {
            float[] v1 = new float [3];
            float[] v2 = new float [3];
            old_img = image;
            new_img = new Bitmap(image);
            
            v1[0] = 0;
        	v1[1] = 1;
	        v2[0] = -1;
	        v2[1] = 1;
            
            double contrast = 1.0;

	        for(int x = 0; x < old_img.Width - 1; x++){
		        for(int y = 0; y < old_img.Height; y++){
			        double tl = -1.0;
			        double tm = -1.0;
			        double tr = -1.0;
			        double ml =-1.0;
			        double mm =-1.0;
			        double mr =-1.0;
			        double bl =-1.0;
			        double bm =-1.0;
			        double br =-1.0;
			
			        if (x>0 && y>0) tl= getFastPixel(x-1,y-1)[0];
			        if (y>0) tm=getFastPixel(x,y-1)[0];
			        if (x<old_img.Width-1 && y>0) tr = getFastPixel(x+1,y-1)[0];
			        if (x>0) 
                    {
                        ml =getFastPixel(x-1,y)[0];
				        mm=getFastPixel(x,y)[0];
                    }
			        if (x<old_img.Width-1) mr = getFastPixel(x+1,y)[0];
			        if (x>0 && y<old_img.Height-1)	bl = getFastPixel(x-1,y+1)[0];
			        if (y<old_img.Height-1) bm=getFastPixel(x,y+1)[0];
			        if (x<old_img.Width-1 && y<old_img.Height-1) br=getFastPixel(x+1,y+1)[0];
			
			        if (tl==-1.0) tl=mm;
			        if (tm==-1.0) tm=mm;
			        if (tr==-1.0) tr=mm;
			        if (ml==-1.0) ml=mm;
			        if (mr==-1.0) mr=mm;
			        if (bl==-1.0) bl=mm;
			        if (bm==-1.0) bm=mm;
			        if (br==-1.0) br=mm;
			
			        double vx =0.0;
			        double vy =0.0;
			        double vz =1.0;
			
			        double isq2 = 1.0/Math.Sqrt(2.0);
			        double sum = 1.0+isq2+isq2;
						
			        double al =(tl*isq2+ml+bl*isq2)/sum;
			        double ar =(tr*isq2+mr+br*isq2)/sum;
			        double at =(tl*isq2+tm+tr*isq2)/sum;
			        double ab =(bl*isq2+bm+br*isq2)/sum;		

			        vx = (al-ar)/255.0*contrast;
			        vy = (at-ab)/255.0*contrast;

			        double m =Math.Sqrt(vx*vx+vy*vy+vz*vz);
			        vx=(Math.Sign(vx)*vx)/m;
			        vy=(Math.Sign(vy)*vy)/m;
			        vz=vz/m;

                    int r= (int) (vx*128.5+128.5);
			        int g= (int) (vy*128.5+128.5);
			        int b= (int) (vz*255.0);
			
			        if (r<0) r=0;
			        if (r>255) r=255;
			        if (g<0) g=0;
			        if (g>255) g=255;
			        if (b<0) b=0;
			        if (b>255) b=255;

                    setFastPixel(x, y, r, g, b);
		        }
	        }



            return getNewImage(true);
        }

    }
}
